package com.luomo.java.juc.producerconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LiuMei
 * @date 2021-04-12.
 */
public class LockShareData extends ShareData {


    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    @Override
    public void add() {
        lock.lock();
        try {
            while (number != 0) {
                try {
                    //不能生产，等待
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "\t生产");
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

    @Override
    public void sub() {
        lock.lock();
        try {
            while (number == 0) {
                try {
                    //不能消费，等待
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "\t消费");
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
